package persist

import (
	"log"
	"gopkg.in/olivere/elastic.v5"
	"context"
	"crawlerm/engine"
	"github.com/pkg/errors"
)

func ItemServer() (chan engine.Item,error){
	client,err:=elastic.NewClient(
		//内网不能sniff
		elastic.SetSniff(false))

	if err!=nil{
		return nil,err
	}
	out:=make(chan engine.Item)
	go func() {
		itemCount:=0
		for{
			item:=<-out
			log.Printf("获取到信息#%d : %v",itemCount,item)
			itemCount++

			err:=save(client,item)

			 if err!=nil{
			 	log.Print("Item Saver:error"+" saveing item %v  : %v",item,err)
			 }
		}
	}()
	return out,nil
}

func save(client *elastic.Client,item engine.Item)(err error){

	if item.Type==""{
		return errors.New("不能为空类型type")
	}
	indexService:=client.Index().
		Index("dating_profile").
		Type(item.Type).
		BodyJson(item)

	if item.Id!=""{
		indexService.Id(item.Id)
	}
	_,err=indexService.
		Do(context.Background())

	if err!=nil{
		return err
	}
	return nil

}


